package com.woniu.config;

import com.woniu.filter.JwtTokenAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
//@EnableGlobalMethodSecurity(securedEnabled = true)
public class MyWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter;

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(HttpMethod.GET,
                "/v2/**",
                "/v3/**",
                "/swagger-resources/**",
                "/configuration/**",
                "/swagger-ui.html/**",
                "/webjars/**",
                "img.icons/**",
                "/doc.html");
        super.configure(web);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.httpBasic().and().authorizeRequests().anyRequest().authenticated(); //关闭httpBasic认证
        //需要放行的url在这里配置,必须要放行/login和/login.html,不然会报错
        http.authorizeRequests().antMatchers(
                "/v2/**",
                "/v3/**",
                "/swagger-resources/**",
                "/configuration/**",
                "/swagger-ui.html/**",
                "/webjars/**",
                "img.icons/**",
                "/doc.html",
                "/doc.html","/login", "/login.html","/js/**","/css/**","/index","/index.html")
                .permitAll().anyRequest().authenticated()
                //登录认证成功后默认转跳的路径
//                .defaultSuccessUrl("/home")
//                .failureForwardUrl("/error1")
//                .failureUrl("/error1").permitAll();
                .and()
                //添加一个过滤器到指定过滤器前面
                .addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        //关闭CSRF跨域
        http.csrf().disable();

        //关闭session最严格的策略
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

}
